package task

import (
	"errors"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"minefieldplatform-go/app/service/cmdb"
	"minefieldplatform-go/library"
	"os"
	"reflect"
	"strings"
)

func MachineList(r *ghttp.Request) {
	gpuList, gpuCount := cmdb.GetGpuList()
	StorageList, storageCount := cmdb.GetStorageList()

	var a []interface{}

	if reflect.TypeOf(gpuList).Kind() == reflect.Slice {
		s := reflect.ValueOf(gpuList)
		for i := 0; i < s.Len(); i++ {
			ele := s.Index(i)
			a = append(a, ele.Interface().(interface{}))
		}
	}
	if reflect.TypeOf(StorageList).Kind() == reflect.Slice {
		s := reflect.ValueOf(StorageList)
		for i := 0; i < s.Len(); i++ {
			ele := s.Index(i)
			a = append(a, ele.Interface().(interface{}))
		}
	}

	count := gpuCount + storageCount

	r.Response.WriteJson(g.Map{
		"code":  0,
		"msg":   "",
		"count": count,
		"data":  a,
	})
}

func StorageTask(r *ghttp.Request) {
	var data = g.Map{
		"taskname": r.Get("taskname"),
		"ip":       r.Get("ip"),
		"desc":     r.Get("desc"),
	}

	var ip []string
	a := gconv.String(data["ip"])
	b := gconv.String(data["desc"])
	ip = strings.Split(a, ",")

	for _, i := range ip {
		go func(i, b string) {
			res, err := library.RunSsh(i, b)
			if err != nil {
				fmt.Println(errors.New("这里出错了"))
			} else {
				fmt.Println(res)
			}
		}(i, b)
	}
}

func BashTask(r *ghttp.Request) {
	var data = g.Map{
		"taskname": r.Get("taskname"),
		"ip":       r.Get("ip"),
		"desc":     r.Get("desc"),
	}
	var ip []string
	a := gconv.String(data["ip"])
	b := gconv.String(data["desc"])
	ip = strings.Split(a, ",")
	command := "/bin/bash /root/tmpbash.sh"
	os.Remove("tmp/tmpbash.sh")
	library.WriteWithIo("tmp/tmpbash.sh", b)
	for _, i := range ip {
		go func(i, command string) {
			resp, err := library.SendFile(i)
			if err != nil {
				fmt.Println(errors.New("文件传输错误"))
			} else {
				fmt.Println(resp)
			}
			res, err := library.RunSsh(i, command)
			if err != nil {
				fmt.Println(errors.New("这里出错了"))
			} else {
				fmt.Println(res)
			}
		}(i, command)
	}
}
